﻿using ScannerApp.Common;
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Drawing;
using ScannerApp.Model;
using AutoUpdate.Log;
using System.Threading;
using static ScannerApp.Common.PopMessageHelper;
using System.Diagnostics;
using static ScannerApp.Model.WorkType;
using Color = System.Windows.Media.Color;
using ColorConverter = System.Windows.Media.ColorConverter;
using System.Windows.Controls.Primitives;
using System.Web.UI.WebControls;

namespace ScannerApp
{
    /// <summary>
    /// Collection.xaml 的交互逻辑
    /// </summary>
    public partial class Collection : Window
    {
        private string def_imgurl = "http://winpro.gerp.top/Images/upload/Basicboar/ZHU.jpg";
        ScanApp.ScanAppSoapClient sa = new ScanApp.ScanAppSoapClient();
        private string lastTm = "";
        private int PrintTimes = 2;
        private string shortNum = "",longNum="", dormName = "" ;
      
        System.Windows.Threading.DispatcherTimer relashTimer = new System.Windows.Threading.DispatcherTimer();
        private System.Windows.Threading.DispatcherTimer disTimer = new System.Windows.Threading.DispatcherTimer();
        IniFiles ini = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\ScanAppConfig.INI");
        IniFiles iniprint = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\PrintIni_Coll.INI");


        public Collection()
        {
            InitializeComponent();
            czy.Text = publicclass.UserName;
        }

        private void close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            MessageBoxResult result = System.Windows.MessageBox.Show("系统是否关闭？", "提示", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();     
                Environment.Exit(0);
            }
            else
            {

            }

        }
        //最小化
        private void close_MouseLeftButtonMin(object sender, MouseButtonEventArgs e)
        {



            WindowState = WindowState.Minimized;


        }
        //关机
        private void close_MouseLeftButtonPower(object sender, MouseButtonEventArgs e)
        {
            tips.SetResourceReference(TextBlock.TextProperty, "oCloseComputer");
            MessageBoxResult result = System.Windows.MessageBox.Show(tips.Text, "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                ProcessStartInfo ps = new ProcessStartInfo();
                ps.FileName = "shutdown.exe";
                ps.Arguments = "-s -t 1";
                Process.Start(ps);
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
            else
            {

            }
        }

        /// <summary>
        /// 2020/9/9 增加扫描电子耳标录入功能（无短号绑定的情况），以年份缩写+日期组合自动生成6位数短号（后续可以人为再进行修改短号名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tm1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) {

            try
            {
                if (e.Key == Key.Enter)
                {
                    this._loading.Visibility = Visibility.Visible;

                    //button1.Focus();
                    LoadData(tm1.Text);
                    tm1.Text = "";
                    this._loading.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                this._loading.Visibility = Visibility.Collapsed;
                ShowModalDialog_value( "错误:" + ex.Message + "！");
                //  PopMessageHelper.ShowMessage("错误:"+ exception.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
               
               // PopMessageHelper.ShowMessage("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                return;
            }



        }
        private void read_Click(object sender, RoutedEventArgs e)
        {
            this._loading.Visibility = Visibility.Visible;

            LoadData(tm1.Text);
            this._loading.Visibility = Visibility.Collapsed;

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
             this.WindowState = System.Windows.WindowState.Maximized;
            //this.Left = 0;
            //this.Top = 0;
            //this.Height = SystemParameters.WorkArea.Height;//获取屏幕的宽高  使之不遮挡任务栏
            //this.Width = SystemParameters.WorkArea.Width;
            tm1.Focus();
             //sysname.Text = publicclass.SystemName;
            string preurl = Common.ConfigHelper.GetEndpointClientAddress("ScanAppSoap");
            yellow.Text = publicclass.DeviceName;
            Uri uri = new Uri(preurl);
            string imageurl = uri.Scheme + "://" + uri.Host + "/" + publicclass.SystemLogo;
            //Console.WriteLine(uri.Host);
            //this.tb_1.Source = new BitmapImage(new Uri(imageurl));
            //tm();
         
            ReflashGridData();
            DataTable lsdt = sa.GetDataTable_Sys_info();
            foreach (DataRow dr in lsdt.Rows)
            {
                try {
                    if (dr["sys_key"].ToString() == "Collection")
                    {
                        PrintTimes = int.Parse(dr["sys_value"].ToString());
                    }
                } catch { }
            }

            relashTimer.Interval = TimeSpan.FromMinutes(1);
            relashTimer.Tick += relashTime;
            relashTimer.Start();

         
            disTimer.Interval = new TimeSpan(0, 0, 0, 3); //参数分别为：天，小时，分，秒。此方法有重载，可根据实际情况调用。
            disTimer.Tick += new EventHandler(disTimer_Tick); //每一秒执行的方法 
           // disTimer.Start();
        }

        private void disTimer_Tick(object source, EventArgs e)
        {
            disTimer.Stop();
            this.ModalDialog1.IsOpen = false;
        }
            private void relashTime(object source, EventArgs e)
        {


            UIAction(() =>
            {
                ReflashGridData();
            });

        }
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        bool sfdy = false;
        void LoadData(string tm)
        {
            if (tm!= "00000000"&&tm!= "00000001"&&tm.Length != 15)
            {
                Tips("ErrorEBWX", false);
                ReflashGridData();
                return;
            }
            if (tm.Length <= 1) {
                Tips("ErrorEBWX", false);
                ReflashGridData();
                return;
            }
           else if (tm == "00000000")//打印保存
            {
                string msg = sa.Update_boar_collection_collection("collection_save", "", zydh.Text.Trim());
                if (zydh.Text.Trim() != "" && msg == "")
                {
                    // printBarCode();
                    string para = "{\"EventType\":\"种禽流程采集\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + zydh.Text + "\",\"Log_Content\":\"" + "【采集保存(状态)】 → 15\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                    string msglog = sa.Sys_log(para);
                }
                else
                {

                    TipsSystem(tm + msg, false);
                    return;
                }
                // Clear();
            }
            else if (tm == "00000001")//提交
            {
                string msg = sa.Update_boar_collection_collection("collection_submit", publicclass.UserName, zydh.Text.Trim());
                if (zydh.Text.Trim() != "" && msg == "")
                {
                    Tips("SuccessDJ", true);
                    string para = "{\"EventType\":\"种禽流程采集\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + zydh.Text + "\",\"Log_Content\":\"" + "【采集保存(提交)】 → 20\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                    string msglog = sa.Sys_log(para);
                  //  Clear("all");
                    ReflashGridData();
                }
                else
                {
                    TipsSystem(tm + msg, false);  
                }
                //Clear();
            }
            else
            {
                 lastTm = tm1.Text.Trim();//记录最后一次条码
                 //bsm.Text = tm1.Text.Trim(); tm1.Text = ""; tm1.Focus();
                Clear("all");
              
                string WorkStyle = ini.IniReadValue("作业类型", "WorkStyle");
              //如果直接生成订单，则直接生成单据
                if (WorkStyle == WorkTypes.DirectWork.ToString()||WorkStyle== WorkTypes.MixWork.ToString())
                {
                    bool IsSave = true;  
                    if (WorkStyle == WorkTypes.MixWork.ToString())//混合
                    {
                        var IsExistOrder = sa.IsExist_collectionOrder(tm);
                        if (!IsExistOrder)
                            WorkStyle = "MixWorkNoOrder";
                        else IsSave = false;
                    }
                    else {//如果有单，直接跳过
                        IsSave = false;
                    }
                    if (IsSave)//是否进行生成单据，不生成就跳过
                    {
                        var r = sa.Save_boar_collection_collection(WorkStyle, publicclass.UserName, publicclass.DeviceName, tm, "", "", publicclass.UserName);
                        if (r.type == ScanApp.ResultType.success)
                        {
                            // tm = r.message;
                            // printBarCode();
                            string para = "{\"EventType\":\"种禽流程采集\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + zydh.Text + "=>类型" + WorkStyle + "\",\"Log_Content\":\"" + "【采集保存(状态)】 → 15\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                            string msglog = sa.Sys_log(para);
                        }
                        else
                        {

                            TipsSystem(tm + r.message, false);
                            return;
                        }
                    }
                  
                }//直接
                

               
                DataTable dt = sa.GetDataTable_Basic_boar_collection(tm);
                if (dt == null)
                {
                    Clear("zy");
                    Tips("ErrorWDYXX", false);
                    ReflashGridData();
                    return;
                }
                else
                {
                    if (dt.Rows.Count <= 0)
                    {
                        Clear("zy");
                        Tips("ErrorWDYXX", false);
                        ReflashGridData();
                        return;
                    }
                    else
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            shortNum = dr["shortcode"].ToString();//简称
                            longNum= dr["barcode"].ToString();
                            pz.Text = dr["cname"].ToString();//品       种
                            barcode.Text = dr["shortcode"].ToString(); //dr["barcode"].ToString();
                            zylx.Text = dr["product_category"].ToString();//品       系
                            zymc.Text = dr["product_name"].ToString();//等       级
                            sccj.Text = dr["LastCollecTime"].ToString();//前次采集
                            nl.Text = dr["nlday"].ToString();//日       龄
                            czlh.Text= dr["corralName"].ToString();//栏       号
                            //yysj.Text = dr["LastEfficaTime"].ToString();
                            string drug = dr["EfficacyState"].ToString() == "1" ? "可用" : "禁用";
                            string colled = dr["CollectionStatus"].ToString() == "1" ? "可采" : "不可采";
                            //zt.Text = "药：" + drug;
                            zt2.Text= colled;
                            dormName = dr["dormName"].ToString();//畜栏
                           // LastCollecTime = DtTostring( dr["LastCollecTime"].ToString(),"yyyy-MM-dd HH:mm");
                           // bool sfky = dr["EfficacyState"].ToString() == "1" && dr["CollectionStatus"].ToString() == "1";
                            //zt.Foreground = dr["EfficacyState"].ToString() == "1" ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red;
                            zt2.Foreground = dr["CollectionStatus"].ToString() == "1" ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red;

                            //是否有效
                             string sfyx = dr["CollectionStatus"].ToString() == "1" ? "cyxzy" : "cwxzy"; ;
                            bsmzt.SetResourceReference(TextBlock.TextProperty, sfyx);
                             bsmzt.Foreground = dr["CollectionStatus"].ToString() == "1" ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red;
                            //dr["status"].ToString() == "N" ? System.Windows.Media.Brushes.Red : System.Windows.Media.Brushes.Green;
                            if (dr["CollectionStatus"].ToString() == "1") sfdy = true; else sfdy = false;
                            string imageurl = "",nexturl="";
                            if (dr["img_url"].ToString() == "")
                                imageurl = def_imgurl;
                            else nexturl = dr["img_url"].ToString();
                          string preurl=  Common.ConfigHelper.GetEndpointClientAddress("ScanAppSoap");
                            //http://winpro.gerp.top/Images/upload/Basicboar/ZHU.jpg
                            Uri uri = new Uri(preurl);
                            imageurl =uri.Scheme+"://"+ uri.Host + "/Images/upload/Basicboar/" + nexturl;

                          
                            ReflashGridData();
                            // Console.WriteLine(uri.Host);
                            //  this.zzimg.Source = new BitmapImage(new Uri(imageurl));
                            //DisplayImg(image, zzimg);

                        }


                    }
                }
            
                    DataTable lsdt = sa.GetDataTable_boar_collection_collection(tm);
                    if (lsdt == null)
                    {
                        Clear("dd");
                        Tips("ErrorNoOrder", false);
                        ReflashGridData();
                        return;
                    }
                    else
                    {
                        if (lsdt.Rows.Count <= 0)
                        {
                            Clear("dd");
                            Tips("ErrorNoOrder", false);
                            ReflashGridData();
                            return;
                        }
                        else
                        {
                            foreach (DataRow dr in lsdt.Rows)
                            {
                                zydh.Text = dr["id"].ToString();
                                //  ddbh.Text = dr["Serialnumber"].ToString();
                                cpsl.Text = dr["quantity"].ToString();
                                mfrl.Text = dr["capacity"].ToString();
                                ddjq.Text = dr["Order_date"].ToString();
                                //yysj.Text = dr["collectDate"].ToString();
                                ddzt.Text = dr["StatusName"].ToString();
                               // dr["StatusName"].ToString();

                            }

                            if (sfdy)
                            {
                          //  LoadData("00000001");//直接显示，打印，提交 
                             printBarCode();
                                                 //先显示数据，再打印，再提交


                        }
                            else
                            {
                                Tips("ErrorNoZY", false);
                            }
                        }
                    }
                
            }
            //printBarCode();
        }

        void Clear(string type)
        {
            if (type == "dd"||type=="all")
            {
                //bsm.Text = "";


                zydh.Text = "";
                //ddbh.Text = "";
                cpsl.Text = "";
                mfrl.Text = "";
                ddjq.Text = "";
                //yysj.Text = "";
                ddzt.Text = "";
 
            }
            if (type == "zy" || type == "all")
            {
                pz.Text = "";
                zylx.Text = "";
                zymc.Text = "";
                sccj.Text = "";
                //jqyy.Text = "";
                //yysj.Text = "";
                //zt.Text = "";
                zt2.Text = "";
                //是否有效
                bsmzt.Text = "";
                barcode.Text = "";
                nl.Text = "";

                // Console.WriteLine(uri.Host);
                // this.zzimg.Source = new BitmapImage(new Uri(def_imgurl));

            }

            shortNum = "";
            longNum = "";
        }

     

        void DisplayImg(System.Drawing.Image image,System.Windows.Controls.Image cimage)
        {
            //System.Drawing.Image image = BarcodeHelper.GenerateCZ("00000000", 200, 50);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap
                                                                   // 下行,初始一个 ImageSource 作为 myImage 的Source
            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
            bi.EndInit();
            cimage.Source = bi; // done!
            ms.Close();
        }


        void printBarCode()
        {
            try
            {
                //getPrintText(); 
                //Tuple<string[], string[]> print_str = getPrintText_strs();
                //for (int i = 0; i < print_str.Item1.Length; i++)
                //{
                //    string[] xy = print_str.Item2[i].Split(',');
                //   int x= StrToInt(xy[0]);
                //   int y= StrToInt(xy[1]);
                //    //e.Graphics.DrawString(print_str.Item1[i], new Font(new System.Drawing.FontFamily("宋体"), StrToInt(fontsize)), System.Drawing.Brushes.Black, StrToInt(xy[0]), StrToInt(xy[1]));

                //}
                if (ZebarPrint.GetZebarPrintCount() == 0)
                {
                    Tips("ErrorNoPrint", true);
                    ShowModalDialog_value("无有效打印机！");
                    //  PopMessageHelper.ShowMessage("打印机错误:无有效斑马打印机！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

                    return;
                }
                if (ZebarPrint.GetZebarPrintCount() > 1)
                {
                    Tips("ErrorNoOnlyPrint", true);
                    ShowModalDialog_value("打印机超过一个！");
                    //PopMessageHelper.ShowMessage("打印机错误:斑马打印机超过一个！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

                    return;
                }
                //实例化打印对象
                PrintDocument document = new PrintDocument();
                string s_bar = LoadPrintIni("Setting");
                string[] s = new string[] { };
                if (s_bar.Length > 0) s = s_bar.Split(',');
                //设置打印用的纸张,可以自定义纸张的大小(单位：mm).   当打印高度不确定时也可以不设置
                document.DefaultPageSettings.PaperSize = new PaperSize("Custum", StrToInt( s[0]), StrToInt(s[1]));

                //注册PrintPage事件，打印每一页时会触发该事件
                document.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

                //开始打印
                //document.Print();

               // 打印预览
                //PrintPreviewDialog ppd = new PrintPreviewDialog();
                //ppd.Document = document;
                //ppd.ShowDialog();

                //return;
                try
                {
                    //if (this.CurrentPrintQRCode != null && this.CurrentPrintQRCode.Count() > 0)
                    //{
                    // int printtimes = 2;
                    bool isprint = false;
                    for (int i = 1; i <= PrintTimes; i++)
                    {
                        string errMsg = ZebarPrint.GetZebarPrintStatus();
                        if (errMsg != "")
                        {
                            Tips(errMsg, true);
                            ShowModalDialog_value(errMsg + "！");
                            //PopMessageHelper.ShowMessage("打印机错误:" + errMsg + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

                            return;
                        }
                        TipsSystem("第" + i.ToString() + "张正在打印！", true);
                        document.Print();
                        Thread.Sleep(1000);
                        if (i == PrintTimes) isprint = true;//最后一张，可以提交
                    }
                    if (isprint)//全部打印完成，则提交
                    {
                        Tips("ErrorSubmiting", true);
                        LoadData("00000001");//直接显示，打印，提交 
                    }
                      
                }
                catch (Exception exception)
                {
                    ShowModalDialog_value( "错误:" + exception.Message + "！");
                  //  PopMessageHelper.ShowMessage("错误:"+ exception.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                    
                    document.PrintController.OnEndPrint(document, new PrintEventArgs());
                    return;
                }
              
            }
            catch (Exception e) {
                ShowModalDialog_value( "错误:" + e.Message + "！");
                //  PopMessageHelper.ShowMessage("错误:"+ exception.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                
                //PopMessageHelper.ShowMessage("错误:"+e.Message+"！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]"+ e.Message, LogType.Error, "collection");
                return;
            }
        }
        private void pd_PrintPage(object sender, PrintPageEventArgs e) //触发打印事件
        {


            string workid = zydh.Text;//二维码内容
            string[] s = new string[] { };
           // string text_Content = getPrintText();
            string s_bar=  LoadPrintIni("Barcode");
            if(s_bar.Length > 0) s = s_bar.Split(',');
            int BarcodeWidth = StrToInt( s[0]);//二维码长度，高度
            int BarcodeHeight = StrToInt(s[1]);
            int BarcodeX = StrToInt(s[2]);
            int BarcodeY = StrToInt(s[3]);
            string fontsize = LoadPrintIni("FontSize");
            if (fontsize == "") fontsize = "12";
            //文字
          Tuple<string[], string[]> print_str = getPrintText_strs();
           for(int i = 0; i < print_str.Item1.Length; i++)
            {
               string[] xy= print_str.Item2[i].Split(',');
                e.Graphics.DrawString(print_str.Item1[i], new Font(new System.Drawing.FontFamily("宋体"), StrToInt(fontsize)), System.Drawing.Brushes.Black, StrToInt( xy[0]),StrToInt( xy[1]));

            }//二维码
            e.Graphics.DrawImage(BarcodeHelper.Generate1(workid, BarcodeWidth , BarcodeHeight  ), BarcodeX,BarcodeY, BarcodeWidth, BarcodeHeight);

            //BarcodeHelper.DrawPrint(e, sb.ToString(), pe.WorkID, ImgWidth, ImgHeight);
            // BarcodeHelper.GetPrintWorkIDPicture(bmp2, pe, e);
        }
        //顺序打印
        string getPrintText()
        {

            PrintWorkDocumentEntity pe = new PrintWorkDocumentEntity();
         
            string[] ss = new string[] { };
            string[] s = new string[] { };
            string[] s_dw = new string[] { };
            string s_tp = LoadPrintIni("TitlePara");
            ss = s_tp.Split(',');
            string printpara = "";
            string content = "";
            foreach (string s_t in ss)
            {
                printpara += LoadPrintIni(s_t) + "|";
                if (s_t == "T1") content += zydh.Text + "|";//作业单:
                else if (s_t == "T2") content += longNum + "|";//ID
                else if (s_t == "T3") content += zylx.Text + "|";//品  种:
                else if (s_t == "T4") content += nl.Text + "|";//日  龄:,天
                else if (s_t == "T5") content += publicclass.UserName + "|";//采精员
                else if (s_t == "T6") content += DateTime.Today.ToString("yyyy-MM-dd") + "|";//日  期
                else if (s_t == "T7") content += barcode.Text + "|";//耳  号:
                else if (s_t == "T8") content += czlh.Text + "|";//栏 号
                else if (s_t == "T9") content += dormName + "|";//畜 舍:
                else if (s_t == "T10") content += sccj.Text + "|";//前次采集日期
                else if (s_t == "T11") content += sccj.Text + "|";//前次采集时间

            }
            printpara = RemoveStrLastChar(printpara);
            //printpara.TrimEnd('|');
            content = RemoveStrLastChar(content);
            //string printpara = "作业单:|ID:|品  种:|日  龄:|天|采集员:|日  期:|耳  号:";

            //try
            //{
            //    tips.SetResourceReference(TextBlock.TextProperty, "cprintpara");
            //    printpara = tips.Text; 

            //}
            //catch { 
            //    printpara = "作业单:|ID:|品  种:|日  龄:|天|采集员:|日  期:|耳  号"; }
            s = printpara.Split('|');
            ss = content.Split('|');
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < s.Length; i++)
            {
                if (s[i].IndexOf(',') != -1)//单位
                {
                    s_dw = s[i].Split(',');
                    sb.Append("" + s_dw[0] + " " + ss[i] + " " + s_dw[1] + "\r\n");
                }
                else if (s[i].IndexOf('&') != -1)//时间格式化
                {
                    s_dw = s[i].Split('&');
                    if (s_dw[1] == "") s_dw[1] = "yyyy-MM-dd";//如果没有，默认
                    sb.Append("" + s_dw[0] + " " + DtTostring(ss[i], s_dw[1]) + "\r\n");
                }
                else
                    sb.Append("" + s[i] + " " + ss[i] + "\r\n");
            }
            return sb.ToString();
        }
        //自定义打印，每行自定义XY坐标
        Tuple<string[], string[]> getPrintText_strs()
        {

            PrintWorkDocumentEntity pe = new PrintWorkDocumentEntity(); 
            string[] ss = new string[] { };
            string[] s = new string[] { };
            string[] s_dw = new string[] { };
            string s_tp = LoadPrintIni("TitlePara");
            ss = s_tp.Split(',');
            string printpara = "";
            string content = "";
            foreach (string s_t in ss)
            {
                printpara += LoadPrintIni(s_t) + "|";
                if (s_t == "T1") content += zydh.Text + "|";//作业单:
                else if (s_t == "T2") content += longNum + "|";//ID
                else if (s_t == "T3") content += zylx.Text + "|";//品  种:
                else if (s_t == "T4") content += nl.Text + "|";//日  龄:,天
                else if (s_t == "T5") content += publicclass.UserName + "|";//采精员
                else if (s_t == "T6") content += DateTime.Today.ToString("yyyy-MM-dd") + "|";//日  期
                else if (s_t == "T7") content += barcode.Text + "|";//耳  号:
                else if (s_t == "T8") content += czlh.Text + "|";//栏 号
                else if (s_t == "T9") content += dormName + "|";//畜 舍:
                else if (s_t == "T10") content += sccj.Text + "|";//前次采集日期
                else if (s_t == "T11") content += sccj.Text + "|";//前次采集时间

            }
            printpara = RemoveStrLastChar(printpara);
                //printpara.TrimEnd('|');
            content = RemoveStrLastChar(content);  
            //string printpara = "作业单:|ID:|品  种:|日  龄:|天|采集员:|日  期:|耳  号:";

            //try
            //{
            //    tips.SetResourceReference(TextBlock.TextProperty, "cprintpara");
            //    printpara = tips.Text; 

            //}
            //catch { 
            //    printpara = "作业单:|ID:|品  种:|日  龄:|天|采集员:|日  期:|耳  号"; }
            s = printpara.Split('|');
            ss = content.Split('|');
           // StringBuilder sb = new StringBuilder();
            string[] ret_s= new string[s.Length];
            string[] ret_s_XY = new string[s.Length];
            for (int i = 0; i < s.Length; i++) 
            {
                if (s[i] == "") continue;
                string[] title = s[i].Split(new string[] { "_XY_" }, StringSplitOptions.RemoveEmptyEntries);
                ret_s_XY[i] = title[0];
                string t= title[1];
                if (t.IndexOf(',') != -1)//单位
                {
                    s_dw = t.Split(',');
                    ret_s[i]=  s_dw[0] + " " + ss[i] + " " + s_dw[1]  ;
                    //sb.Append("" + s_dw[0] + " " + ss[i] + " " + s_dw[1] + "\r\n");
                }
                else if (t.IndexOf('&') != -1)//时间格式化
                {
                    s_dw = t.Split('&');
                    if (s_dw[1] == "") s_dw[1] = "yyyy-MM-dd";//如果没有，默认
                    ret_s[i] = s_dw[0] + " " + DtTostring(ss[i], s_dw[1]);
                    //sb.Append("" + s_dw[0] + " " + DtTostring(ss[i], s_dw[1]) + "\r\n");
                }
                else ret_s[i] = t + " " + ss[i];
                // sb.Append("" + s[i] + " " + ss[i] + "\r\n");
            }
            return new Tuple<string[], string[]>(ret_s,ret_s_XY);
        }

        //右边处理列表
        void ReflashGridData()
        {
            try
            {
                DataSet lsdt = sa.GetCollection_all_data();
                // var r = SQLLogic.GetList_boar_collection("");
                //if (r.Item1)
                //datagrid1.ItemsSource = lsdt.Tables[0].DefaultView;
                datagrid2.ItemsSource = lsdt.Tables[1].DefaultView;
                //设置网格线
                datagridwcl.ItemsSource = lsdt.Tables[0].DefaultView;
                //datagrid1.GridLinesVisibility = DataGridGridLinesVisibility.All;
            }
            catch(Exception e) { }
        }

        void Tips(string msg,bool flag)
        {
            UIAction(() =>
            {

                if (flag)
                {
                    tips.SetResourceReference(TextBlock.TextProperty, msg);
                    //tips.Text =    msg + "！";
                    tips.Foreground = System.Windows.Media.Brushes.Green;
                }
                else
                {
                    tips.Foreground = System.Windows.Media.Brushes.Red;
                  //  tips.Text = "错误:" + msg + "！";
                    tips.SetResourceReference(TextBlock.TextProperty, msg);
                }

                    tips.Visibility = Visibility.Visible;
            });
            System.Threading.Timer timer = new System.Threading.Timer(
                        (state) =>
                        {
                            tips.Dispatcher.BeginInvoke((Action)delegate ()
                            {

                                tips.Text = "";
                                tips.Visibility = Visibility.Collapsed;
                            });


                        }, null, 3000, Timeout.Infinite);
         
          //  PopMessageHelper.ShowMessage("错误:"+msg +"！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);          
            Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]"+msg, LogType.Error, "collection");
            this._loading.Visibility = Visibility.Collapsed;
            //     PopMessageHelper.HideShowMessage();  
            tm1.Focus(); 
        }
        /// <summary>
        /// 系统报错
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="flag"></param>
        void TipsSystem(string msg, bool flag)
        {
            UIAction(() =>
            {

                if (flag)
                {
                    tips.Text = msg + "！";
                    tips.Foreground = System.Windows.Media.Brushes.Green;
                }
                else
                {
                    tips.Foreground = System.Windows.Media.Brushes.Red;
                       tips.Text =  msg + "！";
                   
                }

                tips.Visibility = Visibility.Visible;
            });
            System.Threading.Timer timer = new System.Threading.Timer(
                        (state) =>
                        {
                            tips.Dispatcher.BeginInvoke((Action)delegate ()
                            {

                                tips.Text = "";
                                tips.Visibility = Visibility.Collapsed;
                            });


                        }, null, 3000, Timeout.Infinite);

            //  PopMessageHelper.ShowMessage("错误:"+msg +"！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);          
            Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]" + msg, LogType.Error, "collection");
            this._loading.Visibility = Visibility.Collapsed;
            //     PopMessageHelper.HideShowMessage();  
            tm1.Focus();
        }

        void UIAction(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }

        private void Datagrid1_SourceUpdated(object sender, DataTransferEventArgs e)
        {

        }

        private void Dlg_Close_Click(object sender, RoutedEventArgs e)
        {
            this.ModalDialog1.IsOpen = false;
        }

        private void ShowModalDialog_value(  string tips)
        {
            this.ModalDialog1.IsOpen = true;
            errtip.Text = tips;
            disTimer.Start();
             
           
            // this.MainPanel.IsEnabled = !bShow;
        }

        private void Txtsd_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void datagridwcl_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            try
            {
                //CollectionEntity item = e.Row.Item as CollectionEntity;
                //CollectionEntity item = (CollectionEntity)e.Row.DataContext;
                 dynamic item = e.Row.Item;
                if (item != null)
                {
                    dynamic item2 = item.Row.ItemArray;
                    //                item.id = e.Row.GetIndex() + 1;
                    if (item2[3].ToString() != "")
                    {
                        //                    e.Row.Background = new SolidColorBrush(Colors.Red);
                        e.Row.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(item2[3].ToString()));

                    }
                }
            }
            catch (Exception ex) { }
        }


        private string LoadPrintIni(string type)
        {
            string s = "";
            try
            {
                  s = iniprint.IniReadValue("Collection", type);
            }
            catch { }

            return s;
        }
        private static int StrToInt(string s)
        {
            int i = 0;
            try
            {

                i = int.Parse(s);
            }
            catch { }

            return i;

        }

        private static string DtTostring(string s,string f)
        {
            string i = "";
            try
            {

                i = DateTime.Parse(s).ToString(f);
            }
            catch { }

            return i;

        }
        //去除最后一个字符
        private static string RemoveStrLastChar(string originalString) {
            string modifiedString="";
            if (originalString.Length > 0)
            {
                modifiedString = originalString.Remove(originalString.Length - 1);
            }
            else
            {
                modifiedString = originalString;
            }
            return modifiedString;
        }
    }

}
